package nl.hanze.designpatterns.db;

import java.sql.*;
import java.util.Iterator;

public class Executor {
	private static Executor instance = null;
	private static final String URL = "jdbc:mysql://159.253.0.11:3306/";
	private static final String DATABASE = "xktqogaj_dpat";
	private static final String USER = "xktqogaj_dpat";
	private static final String PASSWORD = "designpatterns";
	private static final String SQLDriver = "com.mysql.jdbc.Driver";
	
	private Executor(){
		loadDBDriver();
	}
	
	public static synchronized Executor getInstance(){
		if(instance == null){
			instance = new Executor();
		}
		return instance;
	}
	
	private static void loadDBDriver() {
		try{
			Class.forName(SQLDriver).newInstance();
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	private static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(URL + DATABASE, USER, PASSWORD);
	}
	
	private static ResultSet performQuery(String query) throws SQLException{
		Connection conn = getConnection();
		Statement statement = conn.createStatement();
		return statement.executeQuery(query);
	}
	
	public void executeQuery(String query) throws Exception {
		performQuery(query);
	}
	
	public <T> Iterator<T> getIterator(String query, Class<T> c) throws Exception {
		return new RowIterator<T>(c, performQuery(query));
	}
}
